'use client';

import React, { createContext, useState, useEffect, ReactNode, useContext } from 'react';
import { getInitialBikeCounts, getAllHistoricalFlows, getDailyPredictions, HistoricalFlow, DailyPrediction } from '@/services/api';
import { TimeContext, SIMULATION_START_TIME } from './TimeContext';

type FlowDataMap = Record<string, Record<string, number>>;

interface DataContextType {
  initialCounts: Record<string, number>;
  historicalFlows: FlowDataMap;
  predictedFlows: FlowDataMap;
  isLoading: boolean;
}

export const DataContext = createContext<DataContextType | undefined>(undefined);

export const DataProvider = ({ children }: { children: ReactNode }) => {
  const [initialCounts, setInitialCounts] = useState<Record<string, number>>({});
  const [historicalFlows, setHistoricalFlows] = useState<FlowDataMap>({});
  const [predictedFlows, setPredictedFlows] = useState<FlowDataMap>({});
  const [isLoading, setIsLoading] = useState(true);
  const [currentPredictionDate, setCurrentPredictionDate] = useState<string | null>(null);

  const timeContext = useContext(TimeContext);

  // 1. 应用首次加载时，获取所有基础数据
  useEffect(() => {
    const loadInitialData = async () => {
      setIsLoading(true);
      console.log("Loading initial data...");

      const [counts, history] = await Promise.all([
        getInitialBikeCounts(),
        getAllHistoricalFlows(),
      ]);

      setInitialCounts(counts);

      const historyMap: FlowDataMap = {};
      for (const flow of history) {
        if (!historyMap[flow.community_id]) {
          historyMap[flow.community_id] = {};
        }
        // 修复：同样将历史数据的时间字符串转换为标准 UTC 格式
        const utcSlotString = new Date(flow.time_slot + 'Z').toISOString();
        historyMap[flow.community_id][utcSlotString] = flow.net_flow;
      }
      setHistoricalFlows(historyMap);
      
      console.log("Initial data loaded.");
      setIsLoading(false);
    };
    loadInitialData();
  }, []);

  // 2. 监听当前时间，在跨天时获取新的预测数据
  useEffect(() => {
    if (!timeContext || isLoading) return;

    const { currentTime } = timeContext;
    
    // 修复：直接使用 currentTime 的日期作为我们正在预测的那一天
    const currentDateString = currentTime.toISOString().split('T')[0];
    
    // 获取前一天的日期字符串，作为 API 的查询参数
    const queryDate = new Date(currentTime.getTime() - 24 * 60 * 60 * 1000);
    const queryDateString = queryDate.toISOString().split('T')[0];

    if (currentDateString !== currentPredictionDate) {
      console.log(`Date changed to ${currentDateString}. Fetching predictions based on ${queryDateString}...`);
      setCurrentPredictionDate(currentDateString);

      const fetchPredictions = async () => {
        const predictions = await getDailyPredictions(queryDateString);
        const predictionMap: FlowDataMap = {};
        for (const pred of predictions) {
          if (!predictionMap[pred.community_id]) {
            predictionMap[pred.community_id] = {};
          }
          for (const point of pred.series) {
            // 修复：将后端返回的时间字符串转换为带 'Z' 的标准 UTC 格式
            // "2021-05-03T03:00:00" -> "2021-05-03T03:00:00.000Z"
            const utcSlotString = new Date(point.time_slot + 'Z').toISOString();
            predictionMap[pred.community_id][utcSlotString] = point.predicted_net_flow;
          }
        }
        setPredictedFlows(predictionMap);
        console.log(`Predictions for ${currentDateString} loaded successfully.`);
      };
      fetchPredictions();
    }
  }, [timeContext?.currentTime, isLoading, currentPredictionDate]);

  const value = { initialCounts, historicalFlows, predictedFlows, isLoading };

  return <DataContext.Provider value={value}>{children}</DataContext.Provider>;
};